<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input v-model="params.name" placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>
    <el-button type="primary" @click="addBuilding">添加楼宇</el-button>
    <el-button @click="exportToExcel">导出excel</el-button>
    <el-dialog
      title="添加楼宇"
      :visible="dialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 添加楼宇弹窗 -->
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules">
          <el-form-item label="楼宇名称" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors">
            <el-input v-model="addForm.floors" />
          </el-form-item>
          <el-form-item label="在管面积" prop="area">
            <el-input v-model="addForm.area" />
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <el-input v-model="addForm.propertyFeePrice" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="buildingList"
      >
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
        />
        <el-table-column
          label="楼宇名称"
          width="180"
          prop="name"
        />
        <el-table-column
          label="层数"
          prop="floors"
        />
        <el-table-column
          label="在管面积(m²)"
          width="120"
          prop="area"
        />
        <el-table-column
          label="物业费(元/m²)"
          width="120"
          prop="propertyFeePrice"
        />
        <el-table-column
          label="状态"
          prop="status"
        >
          <template #default="scope">
            {{ formatStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
        >
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              @click="edit(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              @click="confirmDel(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        @current-change="pageChange"
      />
    </div>

  </div>
</template>

<script>
import { getBuildingListAPI, createBuildingAPI, delBuildingListAPI, editBuildingAPI } from '@/api/building.js'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'Building',
  data() {
    return {
      buildingList: [],
      params: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      total: 0,
      dialogVisible: false,
      addForm: {
        name: '',
        floors: null,
        area: null,
        propertyFeePrice: null
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入楼宇名称', trigger: 'blur' }
        ],
        floors: [
          { required: true, message: '请输入楼宇层数', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入楼宇面积', trigger: 'blur' }
        ],
        propertyFeePrice: [
          { required: true, message: '请输入楼宇物业费', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getBuildingList()
  },
  methods: {
    async getBuildingList() {
      const res = await getBuildingListAPI(this.params)

      this.buildingList = res.data.rows
      console.log(res.data.total)
      this.total = res.data.total
    },
    formatStatus(status) {
      const Map = {
        0: '租赁中',
        1: '闲置中'
      }
      return Map[status]
    },
    // 分页切换
    pageChange(page) {
      this.params.page = page
      this.getBuildingList()
    },
    // 序号处理
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1
    },
    // 查询
    doSearch() {
      this.params.page = 1
      this.getBuildingList()
    }, // 添加楼宇弹窗
    addBuilding() {
      this.dialogVisible = true
      this.addForm = {
        name: '',
        floors: null,
        area: null,
        propertyFeePrice: null
      }
    },
    closeDialog() {
      this.dialogVisible = false
    },
    // 确认添加
    confirmAdd() {
      this.$refs.addForm.validate(async(valid) => {
        if (valid) {
          if (this.addForm.id) {
            console.log('编辑')
            await editBuildingAPI(this.addForm)
            this.getBuildingList()
            this.dialogVisible = false
            this.$message({
              message: '编辑成功',
              type: 'success'
            })
          } else {
            console.log('添加')
            await createBuildingAPI(this.addForm)
            this.getBuildingList()
            this.dialogVisible = false
            this.$message({
              message: '添加成功',
              type: 'success'
            })
          }
        }
      })
    },
    // 删除楼宇
    async confirmDel(id) {
      this.$confirm('确认删除当前楼宇吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delBuildingListAPI(id)
        this.getBuildingList()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }).catch(() => {

      })
    },

    // 编辑楼宇
    edit(row) {
      this.dialogVisible = true
      const { id, area, floors, name, propertyFeePrice } = row
      this.addForm = {
        id,
        area,
        floors,
        name,
        propertyFeePrice
      }
    },

    // 导出excel
    async exportToExcel() {
      try {
        const res = await getBuildingListAPI(this.params)
        const tableHeader = ['name', 'floors', 'area', 'propertyFeePrice', 'status']

        // 处理数据
        const sheetData = res.data.rows.map((item) => {
          const _item = {}
          tableHeader.forEach(key => {
            if (key === 'status') {
              _item[key] = item[key] === 0 ? '租赁中' : '闲置中'
            } else {
              _item[key] = item[key]
            }
          })
          return _item
        })

        // 创建工作表
        const worksheet = utils.json_to_sheet(sheetData)

        // 设置列宽
        const columnWidth = [
          { wch: 15 }, // 楼宇名称
          { wch: 10 }, // 层数
          { wch: 15 }, // 在管面积
          { wch: 15 }, // 物业费
          { wch: 10 } // 状态
        ]
        worksheet['!cols'] = columnWidth

        // 创建工作簿
        const workbook = utils.book_new()

        // 将工作表添加到工作簿
        utils.book_append_sheet(workbook, worksheet, '楼宇信息')

        // 修改表头
        utils.sheet_add_aoa(worksheet, [
          ['楼宇名称', '层数', '在管面积(㎡)', '物业费(元/㎡)', '状态']
        ], { origin: 'A1' })

        // 导出文件
        writeFileXLSX(workbook, '楼宇信息表.xlsx')

        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>

.department-container{
  padding:10px;
}
.search-container{
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237,237,237,.9);;
  padding-bottom: 20px;
  .search-label{
    width:100px;
  }
  .search-main{
    width: 220px;
    margin-right: 10px;
  }
}
.page-container{
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>
